package org.example.protocol;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @description: 序列化枚举类
 * @author: feixiang.li
 * @date: 2025-01-02 21:58
 */
@Slf4j
@Getter
public enum Algorithm implements RpcSerialize {

    // 设置json为1
    FASTJSON(1) {
        @Override
        public <T> T deserialize(byte[] bytes, Class<T> clazz) {
            Gson gson = new GsonBuilder().registerTypeAdapter(Class.class, new ClassCodec()).create();
            String json = new String(bytes, StandardCharsets.UTF_8);
            return gson.fromJson(json, clazz);
        }

        @Override
        public <T> byte[] serialize(T object) {
            Gson gson = new GsonBuilder().registerTypeAdapter(Class.class, new ClassCodec()).create();
            String json = gson.toJson(object);
            return json.getBytes(StandardCharsets.UTF_8);
        }
    },

    // 其他可能的算法，可以扩展
    XML(2) {
        @Override
        public <T> T deserialize(byte[] data, Class<T> clazz) {
            // 假设是某种XML反序列化逻辑
            return null; // TODO: 添加XML的反序列化实现
        }

        @Override
        public <T> byte[] serialize(T object) {
            // 假设是某种XML序列化逻辑
            return new byte[0]; // TODO: 添加XML的序列化实现
        }
    },
    JAVA(3) {
        @Override
        public <T> T deserialize(byte[] data, Class<T> clazz) {
            // 假设是某种Java反序列化逻辑
            try {
                ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
                return (T) ois.readObject();
            } catch (IOException | ClassNotFoundException e) {
                throw new RuntimeException("反序列化失败", e);
            }
        }

        @Override
        public <T> byte[] serialize(T object) {
            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(bos);
                oos.writeObject(object);
                return bos.toByteArray();
            } catch (IOException e) {
                throw new RuntimeException("序列化失败", e);
            }
        }
    };

    private final int value;

    // 枚举构造函数，赋值
    Algorithm(int value) {
        this.value = value;
    }

    // 静态方法用于根据value获取相应的算法
    public static RpcSerialize getByValue(int value) {
        for (Algorithm algorithm : values()) {
            if (algorithm.getValue() == value) {
                return algorithm;
            }
        }
        throw new IllegalArgumentException("Unknown algorithm value: " + value);
    }

}
